package com.cntaiping.aimanager.common.config;

import java.util.Properties;

import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.util.Assert;

/**
 * 事务配置
 * 
 * @author HuoShengyu
 * @date 2018-05-17 16:49:47
 * @version 1.0
 */
@Configuration
@ConditionalOnProperty("spring.data.txExpression")
public class TransactionConfig implements EnvironmentAware {
	private Environment env;
	@Autowired
	private TransactionInterceptor advice;
	@Autowired
	@Qualifier("transactionManager")
	private PlatformTransactionManager txManager;

	/**
	 * 使用默认自动代理事务
	 */
	@Bean
	public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
		return new DefaultAdvisorAutoProxyCreator();
	}

	/**
	 * 事务切点配置
	 */
	@Bean
	public AspectJExpressionPointcutAdvisor aspectJExpressionPointcutAdvisor() {
		AspectJExpressionPointcutAdvisor ajepa = new AspectJExpressionPointcutAdvisor();
		Properties prop = new Properties();
		prop.setProperty("add*", "PROPAGATION_REQUIRED");
		prop.setProperty("save*", "PROPAGATION_REQUIRED");
		prop.setProperty("delete*", "PROPAGATION_REQUIRED");
		prop.setProperty("update*", "PROPAGATION_REQUIRED");
		prop.setProperty("list*", "PROPAGATION_REQUIRED,readOnly");
		prop.setProperty("find*", "PROPAGATION_REQUIRED,readOnly");
		prop.setProperty("page*", "PROPAGATION_REQUIRED,readOnly");
		prop.setProperty("*WithTxNever", "PROPAGATION_NEVER");// 编程式事务命名方式
		advice.setTransactionAttributes(prop);
		advice.setTransactionManager(txManager);
		ajepa.setAdvice(advice);
		String txExpression = env.getProperty("spring.data.txExpression");
		Assert.notNull(txExpression, "The txExpression must not be null");
		ajepa.setExpression(txExpression);
		return ajepa;
	}

	@Override
	public void setEnvironment(Environment env) {
		this.env = env;
	}
}
